@extends('dashboard.includes.master')
@section('title', 'Add Template')

@section('css')
    <link href="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.snow.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    <style>
        #preview-container {
            border: 1px solid #ccc;
            padding: 15px;
            min-height: 200px;
            background: #fff;
            display: none;
        }
    </style>
@endsection

@section('content')
<div class="col-xl-12">
    <div class="row">
        <div class="col-xl-12">
            <div class="card custom-card">
                @if(session('success'))
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        {{ session('success') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                @endif

                <div class="card-body">
                    <form action="{{ route('tempelete.store') }}" method="POST" enctype="multipart/form-data" id="mainForm">
                        @csrf
                        <div class="row gy-4">
                            <div class="mb-3 col-4">
                                <label for="subject" class="form-label">Subject</label>
                                <input class="form-control @error('subject') is-invalid @enderror" type="text" name="subject" placeholder="Subject" value="{{ old('subject') }}">
                                @error('subject')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                @enderror
                            </div>

                            <div class="col-12">
                                <textarea name="body" id="body" style="display: none;"></textarea>

                                <div id="toolbar-container" class="mb-2"></div>
                                <div id="editor2" style="min-height: 200px;"></div>
                                <div id="preview-container" class="mt-3"></div>

                                <button type="button" id="preview-btn" class="btn btn-secondary mt-3">Preview HTML</button>

                                @error('body')
                                    <span class="invalid-feedback d-block mt-2">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <div class="col-12 mt-4">
                            <button type="submit" class="btn btn-primary">Create</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('js')
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // toastr إعدادات
    toastr.options = {
        closeButton: true,
        progressBar: true,
        positionClass: 'toast-top-right'
    };

    hljs.configure({ languages: ['html', 'xml'] });

    const toolbarOptions = [
        [{ 'font': [] }, { 'size': [] }],
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'script': 'sub'}, { 'script': 'super' }],
        [{ 'header': '1' }, { 'header': '2' }, 'blockquote', 'code-block'],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }, { 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'direction': 'rtl' }, { 'align': [] }],
        ['link', 'image', 'video', 'formula'],
        ['clean']
    ];

    const quill = new Quill('#editor2', {
        modules: {
            syntax: true,
            toolbar: toolbarOptions
        },
        theme: 'snow'
    });

    const previewBtn = document.getElementById('preview-btn');
    const editorContainer = document.getElementById('editor2');
    const previewContainer = document.getElementById('preview-container');
    const form = document.getElementById('mainForm');
    const bodyTextarea = document.getElementById('body');

    let isPreviewMode = false;

    // زر المعاينة
    previewBtn.addEventListener('click', function () {
        isPreviewMode = !isPreviewMode;
        if (isPreviewMode) {
            previewBtn.textContent = 'Back to Editor';
            editorContainer.style.display = 'none';
            previewContainer.style.display = 'block';
            previewContainer.innerHTML = quill.root.innerHTML;
        } else {
            previewBtn.textContent = 'Preview HTML';
            editorContainer.style.display = 'block';
            previewContainer.style.display = 'none';
        }
    });

    // تنسيق الروابط وأرقام الهواتف
    function formatLinksAndPhones() {
        const text = quill.getText();
        const urlRegex = /(https?:\/\/[^\s<]+|www\.[^\s<]+|[^\s<]+\.(com|net|org|gov|edu|info|io)[^\s<]*)/gi;
        const phoneRegex = /(\+?\d[\d\s\-]{7,}\d)/g;

        const delta = quill.getContents();
        const plainText = delta.ops.map(op => op.insert).join('');
        const newDelta = new Quill.import('delta')();

        const lines = plainText.split('\n');
        lines.forEach((line, index) => {
            let lastIndex = 0;
            const matches = [];
            let match;

            while ((match = urlRegex.exec(line)) !== null) {
                matches.push({ index: match.index, text: match[0], type: 'url' });
            }
            while ((match = phoneRegex.exec(line)) !== null) {
                matches.push({ index: match.index, text: match[0], type: 'phone' });
            }
            matches.sort((a, b) => a.index - b.index);

            matches.forEach(match => {
                if (lastIndex < match.index) {
                    newDelta.insert(line.slice(lastIndex, match.index));
                }
                if (match.type === 'url') {
                    const href = match.text.startsWith('http') ? match.text : 'https://' + match.text;
                    newDelta.insert(match.text, { link: href });
                } else {
                    const phone = match.text.replace(/\s|-/g, '');
                    newDelta.insert(match.text, { link: 'tel:' + phone });
                }
                lastIndex = match.index + match.text.length;
            });

            if (lastIndex < line.length) {
                newDelta.insert(line.slice(lastIndex));
            }

            if (index < lines.length - 1) newDelta.insert('\n');
        });

        quill.setContents(newDelta);
    }

    // حفظ المحتوى في textarea قبل الإرسال
    form.addEventListener('submit', function (e) {
        formatLinksAndPhones(); // تطبيق التنسيق
        bodyTextarea.value = quill.root.innerHTML;
    });
});
</script>
@endsection
